package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.govern.gateway.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;

/**
 * @author Kidy
 * @date 2020/7/15 23:19
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private AuthService authService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //从cookie获取身份令牌
        String token = authService.getTokenFromCookie(request);
        if (StringUtils.isBlank(token)) {
            this.access_denied();
            return null;
        }
        //从header中取jwt
        String jwt = authService.getJwtFromHeader(request);
        if (StringUtils.isBlank(jwt)) {
            this.access_denied();
            return null;
        }
        //在redis中判断jwt是否过期
        boolean result = authService.getExpire(token);
        if (!result) {
            this.access_denied();
            return null;
        }
        return null;
    }

    private void access_denied() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        //拒绝访问
        currentContext.setSendZuulResponse(false);
        //设置响应状态码
        currentContext.setResponseStatusCode(HttpURLConnection.HTTP_OK);
        //设置响应信息
        ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String jsonString = JSON.toJSONString(responseResult);
        currentContext.setResponseBody(jsonString);
        //设置响应类型
        response.setContentType("application/json;charset=UTF-8");
    }
}
